package th.retrofit.lib;

public class AnalogDivision {

    /**
     * https://leetcode-cn.com/problems/divide-two-integers/
     * 不使用乘法，除法和mod运算来实现除法运算
     * @param dividend 被除数
     * @param divisor 除数
     * @return 商
     */
    public int divide(int dividend, int divisor) {
        if (dividend == Integer.MIN_VALUE && divisor == -1) {
            return Integer.MAX_VALUE;
        }
        int flag = 0;
        if (dividend > 0) {
            flag++;
            dividend = -dividend;
        }
        if (divisor > 0) {
            flag++;
            divisor = -divisor;
        }
        int result = 0;
        if (divisor >= -1) {
            result = -dividend;
        } else {
            while (dividend <= divisor) {
                int temp = 1;
                int tempDivisor = divisor;
                while (dividend - tempDivisor < tempDivisor) {
                    temp += temp;
                    tempDivisor += tempDivisor;
                }
                result += temp;
                dividend -= tempDivisor;
            }
        }
        return flag == 1 ? -result : result;
    }

    public static void main(String[] args) {
        System.out.println(new AnalogDivision().divide(17, 3));
    }

}
